package com.emm.yixun.common.utils;

import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.emm.yixun.common.utils.conf.AppPropertiesFactory;

import cn.jpush.api.JPushClient;
import cn.jpush.api.common.resp.APIConnectionException;
import cn.jpush.api.common.resp.APIRequestException;
import cn.jpush.api.push.PushResult;
import cn.jpush.api.push.model.Message;
import cn.jpush.api.push.model.Options;
import cn.jpush.api.push.model.Platform;
import cn.jpush.api.push.model.PushPayload;
import cn.jpush.api.push.model.audience.Audience;
import cn.jpush.api.push.model.audience.AudienceTarget;
import cn.jpush.api.push.model.notification.IosNotification;
import cn.jpush.api.push.model.notification.Notification;
import cn.jpush.api.utils.StringUtils;

public class AppPushUtils {

	protected static final Logger LOG = LoggerFactory
			.getLogger(AppPushUtils.class);

	public static final String TITLE = "Test from XF example";
	public static final String ALERT = "Test from XF Example - alert";
	public static final String MSG_CONTENT = "Test from XF Example - msgContent";
	public static final String REGISTRATION_ID = "021ec20aee5";
	public static final String TAG = "tag_api";
	private static boolean apnsProduction = true;//false表示测试、ture表示生产

	public static void main(String[] args) {
		pushCommon(REGISTRATION_ID, PushPlatformType.All, ALERT, TITLE, null);
	}

	private static void pushCommon(String registrationId, PushPlatformType type, String alert,
			String title, Map<String, String> extraMap) {
		String appKey = AppPropertiesFactory.getPropertyValue("jpush_AppKey");
		String masterSecret = AppPropertiesFactory.getPropertyValue("jpush_MasterSecret");

		if(type == PushPlatformType.iOS){
			appKey = AppPropertiesFactory.getPropertyValue("jpush_AppKey_ios");
			masterSecret = AppPropertiesFactory.getPropertyValue("jpush_MasterSecret_ios");
		}
		@SuppressWarnings("deprecation")
		JPushClient jpushClient = new JPushClient(masterSecret, appKey, 3);

		PushPayload payload = null;

		if (StringUtils.isEmpty(registrationId)) {
			payload = buildPushObject_alert(type, alert, title, extraMap);
		} else {
			payload = buildPushObject_alert(registrationId, type, alert,
					title, extraMap);
		}

		try {
			PushResult result = jpushClient.sendPush(payload);
			LOG.info("Got result - " + result);
			LOG.info("registrationId" + registrationId+"  - PushPlatformType - " + type+"  - alert - "+alert+"  - title"+title+"  - extraMap - "+extraMap);
		} catch (APIConnectionException e) {
			// Connection error, should retry later
			LOG.error("Connection error, should retry later", e);

		} catch (APIRequestException e) {
			// Should review the error, and fix the request
			LOG.error("Should review the error, and fix the request", e);
			LOG.info("HTTP Status: " + e.getStatus());
			LOG.info("Error Code: " + e.getErrorCode());
			LOG.info("Error Message: " + e.getErrorMessage());
		}
	}

	public static PushPayload buildPushObject_alert(String registrationId,
			PushPlatformType type, String alert, String title,
			Map<String, String> extraMap) {
		if (type == PushPlatformType.iOS) {
			return buildPushObject_ios_alertWithExtras(registrationId, alert,
					extraMap);
		} else if (type == PushPlatformType.Android) {
			return buildPushObject_android_alertWithTitleAndExtras(
					registrationId, alert, title, extraMap);
		} else {
			return buildPushObject_all_alert(alert);
		}
	}

	public static PushPayload buildPushObject_alert(PushPlatformType type,
			String alert, String title, Map<String, String> extraMap) {
		if (type == PushPlatformType.iOS) {
			return buildPushObject_ios_alertWithExtras(alert, extraMap);
		} else if (type == PushPlatformType.Android) {
			return buildPushObject_android_alertWithTitleAndExtras(alert,
					title, extraMap);
		} else {
			return buildPushObject_all_alert(alert);
		}
	}

	/**
	 * 快捷地构建推送对象：所有平台，所有设备，内容为 ALERT 的通知，无其他操作。
	 */
	public static PushPayload buildPushObject_all_alert(String alert) {
		return PushPayload.alertAll(alert);
	}

	/**
	 * 构建Android推送对象，有额外消息Map
	 * 
	 * @param alert
	 *            通知内容
	 * @param title
	 *            通知标题
	 * @param extraMap
	 *            额外消息Map
	 * @return
	 */
	public static PushPayload buildPushObject_android_alertWithTitleAndExtras(
			String alert, String title, Map<String, String> extraMap) {
		return PushPayload.newBuilder().setAudience(Audience.all()).setPlatform(Platform.android())
				.setNotification(Notification.android(alert, title, extraMap))
				.build();
	}

	/**
	 * 构建指定设备的Android推送对象，有额外消息Map
	 * 
	 * @param registrationId
	 *            指定设备
	 * @param alert
	 *            通知内容
	 * @param title
	 *            通知标题
	 * @param extraMap
	 *            额外消息Map
	 * @return
	 */
	public static PushPayload buildPushObject_android_alertWithTitleAndExtras(
			String registrationId, String alert, String title,
			Map<String, String> extraMap) {
		return PushPayload.newBuilder().setPlatform(Platform.android())
				.setAudience(Audience.registrationId(registrationId))
				.setNotification(Notification.android(alert, title, extraMap))
				.build();
	}

	/**
	 * 构建iOS推送对象，有额外消息Map
	 * 
	 * @param alert
	 *            通知内容
	 * @param extraMap
	 *            额外消息Map
	 * @return
	 */
	public static PushPayload buildPushObject_ios_alertWithExtras(String alert,
			Map<String, String> extraMap) {
		return PushPayload
				.newBuilder()
				.setAudience(Audience.all())
				.setPlatform(Platform.ios())
				/*.setNotification(
						Notification
								.newBuilder()
								.addPlatformNotification(
										IosNotification.newBuilder().setSound("alert")
												.setAlert(alert).setBadge(1)
												.addExtras(extraMap).build())
								.build())*/
				.setMessage(Message.newBuilder()
						.setMsgContent(alert)
						.addExtras(extraMap)
						.build())
				.setOptions(
						Options.newBuilder().setApnsProduction(apnsProduction)
								.build()).build();
	}

	/**
	 * 构建指定设备的iOS推送对象，有额外消息Map
	 * 
	 * @param registrationId
	 *            指定设备
	 * @param alert
	 *            通知内容
	 * @param extraMap
	 *            额外消息Map
	 * @return
	 */
	public static PushPayload buildPushObject_ios_alertWithExtras(
			String registrationId, String alert, Map<String, String> extraMap) {
		return PushPayload.newBuilder()
				.setPlatform(Platform.ios())
				.setAudience(Audience.registrationId(registrationId))
				/*.setNotification(
						Notification
								.newBuilder()
								.addPlatformNotification(
										IosNotification.newBuilder().setSound("alert")
												.setAlert(alert).setBadge(1)
												.addExtras(extraMap).build())
								.build())*/
				.setMessage(Message.newBuilder()
						.setMsgContent(alert)
						.addExtras(extraMap)
						.build())
				.setOptions(
						Options.newBuilder().setApnsProduction(apnsProduction)
								.build()).build();
	}
	
	public static PushPayload buildPushObject_ios_audienceMore_messageWithExtras() {
        return PushPayload.newBuilder()
                .setPlatform(Platform.ios())
                .setAudience(Audience.newBuilder()
                        .addAudienceTarget(AudienceTarget.tag("tag1", "tag2"))
                        .addAudienceTarget(AudienceTarget.alias("alias1", "alias2"))
                        .build())
                .setMessage(Message.newBuilder()
                        .setMsgContent(MSG_CONTENT)
                        .addExtra("from", "JPush")
                        .build())
                .build();
    }
	
	public static PushPayload buildPushObject_ios_tagAnd_alertWithExtrasAndMessage(String registrationId, String alert, Map<String, String> extraMap) {
        return PushPayload.newBuilder()
                .setPlatform(Platform.ios())
                .setAudience(Audience.registrationId(registrationId))
                .setNotification(Notification.newBuilder()
                        .addPlatformNotification(IosNotification.newBuilder()
                                .setAlert(ALERT)
                                .setBadge(1)
                                .setSound("alert")
                                .addExtra("from", "JPush")
                                .build())
                        .build())
                 .setMessage(Message.content(MSG_CONTENT))
                 .setOptions(Options.newBuilder()
                         .setApnsProduction(true)
                         .build())
                 .build();
    }

	public void pushMessage(String alert) {
		pushCommon(null, PushPlatformType.All, alert, null, null);
	}

	public void pushMessage(String userId, String alert, String title,
			Map<String, String> extraMap, String deviceType, String deviceToken) {
//		UserTokenDto userTokenDto = new UserTokenDto();
//		userTokenDto.setUserId(Long.valueOf(userId));
//		userTokenDto.setStatus(StatusEnum.LOGINED.getNo());
//		UserToken userToken = userTokenService.selectByDto(userTokenDto);
//		if(null != userToken){
//			if(userToken.getDeviceToken() != null && !"".equals(userToken.getDeviceToken())){
				if("1".equals(deviceType)){//设备类型：1=ANDROID；2=IOS；
					pushCommon(deviceToken, PushPlatformType.Android, alert, title, extraMap);
					return;
				}else if("2".equals(deviceType)){//设备类型：1=ANDROID；2=IOS；
					pushCommon(deviceToken, PushPlatformType.iOS, alert, title, extraMap);
					return;
				}else{
					pushCommon(deviceToken, PushPlatformType.All, alert, title, extraMap);
					return;
				}
//			}
//		}
		//throw new XFUNCheckedException("9999","没有找到会员对应的设备");
	}

	public void pushMessage(PushPlatformType type, String alert, String title,
			Map<String, String> extraMap) {
		pushCommon(null, type, alert, title, extraMap);
	}
	
	enum PushPlatformType {
		All, iOS, Android
	}
}
